<template>
  <view>
    <!-- 当前代节点 -->
    <view
      class="tree-node"
      :class="{ 'target-node': isTargetNode }"
      :data-person-id="person.id"
      :style="{ left: `${nodeX}px`, top: `${nodeY}px` }"
    >
      <view
        class="node-card"
        :class="{ male: person.gender === 1, female: person.gender === 0 || person.gender === 2 }"
      >
        <!-- <view class="avatar-container">
          <image v-if="person.photoUrl" :src="person.photoUrl" mode="aspectFill" class="avatar"/>
          <text v-else class="avatar-text">{{ getAvatarText(person) }}</text>
        </view> -->
        <view class="node-info">
          <text class="node-name">{{ person.firstName }}{{ person.lastName }}</text>
          <text v-if="person.remark" class="node-generation">{{ person.remark }}</text>
          <text class="node-generation">第{{ generation }}世</text>
          <view
            class="status-icon"
            :class="{ alive: person.alive === 1, deceased: person.alive === 0 }"
          ></view>
        </view>
        <!-- 弹出菜单，使用相对定位 -->
        <view
          v-if="showMenu && currentMenuPerson === person"
          class="node-menu"
          :style="menuStyle"
          @click.stop
        >
          <view v-for="item in menuList" :key="item.label" class="menu-item" @click="item.action">
            {{ item.label }}
          </view>
        </view>
      </view>
    </view>
    <!-- 配偶节点 -->
    <template v-if="person.spouseList && person.spouseList.length > 0">
      <view
        v-for="(spouse, spouseIdx) in person.spouseList"
        :key="`spouse-${level}-${index}-${spouseIdx}`"
        class="tree-node"
        :class="{ 'target-node': spouse.id === targetPersonId }"
        :data-person-id="spouse.id"
        :style="{ left: `${spouseX(spouseIdx)}px`, top: `${nodeY}px` }"
      >
        <view
          class="node-card"
          :class="{ male: spouse.gender === 1, female: spouse.gender === 0 || spouse.gender === 2 }"
        >
          <view class="avatar-container">
            <image v-if="spouse.photoUrl" :src="spouse.photoUrl" mode="aspectFill" class="avatar" />
            <text v-else class="avatar-text">{{ getAvatarText(spouse) }}</text>
          </view>
          <view class="node-info">
            <text class="node-name">{{ spouse.firstName }}{{ spouse.lastName }}</text>
            <text v-if="spouse.remark" class="node-generation">{{ spouse.remark }}</text>
            <view
              class="status-icon"
              :class="{ alive: spouse.alive === 1, deceased: spouse.alive === 0 }"
            ></view>
          </view>
          <!-- 配偶节点弹出菜单 -->
          <view
            v-if="showMenu && currentMenuPerson === spouse"
            class="node-menu"
            :style="menuStyle"
            @click.stop
          >
            <view
              v-for="item in spouseMenuList"
              :key="item.label"
              class="menu-item"
              @click="item.action"
            >
              {{ item.label }}
            </view>
          </view>
        </view>
      </view>

      <!-- 连接线 -->
      <view
        class="connector-line"
        :style="{
          left: `${connectorX}px`,
          top: `${connectorY}px`,
          width: `${spouseConnectorWidth}px`,
          height: '2px',
        }"
      ></view>
      <!-- 心形 (每个配偶一个) -->
      <view
        v-for="(spouse, spouseIdx) in person.spouseList"
        :key="`heart-${level}-${index}-${spouseIdx}`"
        class="heart-icon"
        :style="{ left: `${heartX(spouseIdx)}px`, top: `${heartY}px` }"
      >
        ❤
      </view>
    </template>
    <!-- 到下一代的连接线 -->
    <template v-if="person.children && person.children.length > 0">
      <view
        class="connector-line vertical"
        :style="{ left: `${parentX}px`, top: `${verticalConnectorY}px`, height: '15px' }"
      ></view>

      <!-- 下一代横向连接线 -->
      <view
        v-if="person.children.length > 1"
        class="connector-line"
        :style="{
          left: `${parentX}px`,
          top: `${horizontalConnectorY - 15}px`,
          width: `${childrenConnectorWidth}px`,
        }"
      ></view>

      <!-- 递归渲染下一代 -->
      <template
        v-for="(child, childIdx) in person.children"
        :key="`child-${level}-${index}-${childIdx}`"
      >
        <!-- 子代垂直连接线 -->
        <view
          class="connector-line vertical"
          :style="{
            left: `${childConnectorX(childIdx)}px`,
            top: `${horizontalConnectorY - 15}px`,
            height: '15px',
          }"
        ></view>
        <!-- 递归调用下一代 -->
        <!-- 递归渲染家谱树 -->
        <genealogy-generation-tree-concat
          :person="child"
          :generation="generation + 1"
          :level="level + 1"
          :index="childIdx"
          :parent-x="childConnectorX(childIdx)"
          :parent-y="nextGenerationY"
          :target-person-id="targetPersonId"
        />
      </template>
    </template>
  </view>
  <AddChildModal
    v-if="showAddChildModal"
    :visible="showAddChildModal"
    :familyOptions="familyOptions"
    :zibeiOptions="zibeiOptions"
    :genderOptions="genderOptions"
    :aliveOptions="aliveOptions"
    @close="showAddChildModal = false"
    @submit="handleAddChild"
  />
</template>

<script lang="ts" setup>
import {
  ref,
  computed,
  onMounted,
  onBeforeUnmount,
  type CSSProperties,
  defineAsyncComponent,
  watch,
  nextTick,
} from "vue";
import AddChildModal from "@/pages/genealogy/person/components/AddChildModal.vue";
// 异步加载递归组件
// const GenealogyGeneration = defineAsyncComponent(() => import('@/pages/mine/process/components/tree.vue'));
import GenealogyGenerationTreeConcat from "@/pages/mine/process/components/treeConcat.vue"; // 引入 tree.vue 组件
// 定义接口
interface Person {
  id: string;
  firstName: string;
  lastName: string;
  photoUrl?: string;
  gender: number;
  alive?: number;
  remark?: string;
  spouseList?: Person[];
  children?: Person[];
  parentId?: string; // 新增parentId属性
  flag?: number; // 配偶标识
}

// 定义props
interface Props {
  person: Person;
  generation: number;
  level: number;
  index: number;
  parentX: number;
  parentY: number;
  targetPersonId?: string; // 新增：目标节点ID，用于定位
}

const props = defineProps<Props>();

// 定义事件
const emit = defineEmits<{
  "node-click": [person: Person];
  "add-parent": [person: Person];
  "add-child": [person: Person];
  "view-info": [person: Person];
  "add-spouse": [person: Person];
  "edit-info": [person: Person];
}>();

// 添加菜单显示状态
const showMenu = ref(false);
const currentMenuPerson = ref<Person | null>(null);

// 节点定位相关
const isTargetNode = computed(() => {
  return props.targetPersonId === props.person.id;
});

const isTargetSpouse = computed(() => {
  if (!props.person.spouseList) return false;
  return props.person.spouseList.some((spouse) => spouse.id === props.targetPersonId);
});

const isTargetChild = computed(() => {
  if (!props.person.children) return false;
  return props.person.children.some((child) => child.id === props.targetPersonId);
});

// 监听目标节点ID变化，进行定位
watch(
  () => props.targetPersonId,
  (newId) => {
    if (newId && (isTargetNode.value || isTargetSpouse.value || isTargetChild.value)) {
      // 延迟执行，确保DOM已渲染
      nextTick(() => {
        locateTargetNode();
      });
    }
  }
);

// 定位目标节点
const locateTargetNode = () => {
  if (!props.targetPersonId) return;

  let targetElement: Element | null = null;

  // 查找目标节点元素
  if (isTargetNode.value) {
    targetElement = document.querySelector(`.tree-node[data-person-id="${props.targetPersonId}"]`);
  } else if (isTargetSpouse.value) {
    targetElement = document.querySelector(`.tree-node[data-person-id="${props.targetPersonId}"]`);
  } else if (isTargetChild.value) {
    targetElement = document.querySelector(`.tree-node[data-person-id="${props.targetPersonId}"]`);
  }

  if (targetElement) {
    // 滚动到目标节点
    targetElement.scrollIntoView({
      behavior: "smooth",
      block: "center",
      inline: "center",
    });

    // 添加高亮动画
    targetElement.classList.add("target-highlight");

    // 3秒后移除高亮
    setTimeout(() => {
      targetElement?.classList.remove("target-highlight");
    }, 3000);
  }
};

// 计算属性
const spouseConnectorWidth = computed(() => {
  if (!props.person.spouseList || props.person.spouseList.length === 0) {
    return 0; // 如果没有配偶，则没有连接线
  }
  // 连接线从主节点延伸到最后一个配偶节点
  return 100 + (props.person.spouseList.length - 1) * 200;
});

const childrenConnectorWidth = computed(() => {
  const children = props.person.children;
  if (!children || children.length <= 1) {
    return 0;
  }
  const lastChildIndex = children.length - 1;
  // 连接线宽度 = 最后一个子节点的中心X坐标 - 第一个子节点的中心X坐标
  return childConnectorX(lastChildIndex) - childConnectorX(0);
});

// 计算节点位置
const nodeX = computed(() => props.parentX - 40);
const nodeY = computed(() => props.parentY);
const connectorX = computed(() => props.parentX + 40);
const connectorY = computed(() => props.parentY + 90);
const nodeHeight = 180;
const verticalLineHeight = 15;
const horizontalLineHeight = 2;
// 节点宽度
const nodeWidth = 120;
// 计算每个子节点的 left
const childNodeLeft = (childIdx: number) => {
  let left = props.parentX;
  for (let i = 0; i < childIdx; i++) {
    left += getSubtreeWidth(props.person.children[i]);
  }
  return left;
};
const heartX = (spouseIdx: number) => {
  // 第一个爱心在主节点和第一个配偶之间
  if (spouseIdx === 0) {
    return props.parentX + 95;
  }
  // 后续的爱心在前一个配偶和当前配偶之间
  const prevSpouseNodeX = spouseX(spouseIdx - 1);
  const prevSpouseNodeRightEdge = prevSpouseNodeX + 100; // 节点宽度为100px
  // 间隙为100px，将爱心放在中间（已针对图标宽度进行调整）
  return prevSpouseNodeRightEdge + 45;
};

const heartY = computed(() => props.parentY + 81);
const verticalConnectorY = computed(() => props.parentY + nodeHeight);
const horizontalConnectorY = computed(() => verticalConnectorY.value + verticalLineHeight + 7.5);
const nextGenerationY = computed(
  () => props.parentY + nodeHeight + verticalLineHeight + horizontalLineHeight
);

// 计算配偶位置（每个配偶占用200px空间）
const spouseX = (spouseIdx: number) => {
  return props.parentX + 90 + spouseIdx * 120;
};

// 递归计算某个节点（含其所有子孙）的总宽度
const getSubtreeWidth = (person: Person): number => {
  let totalWidth = 120; // 当前节点的宽度
  // 计算配偶的宽度
  if (person.spouseList && person.spouseList.length > 0) {
    totalWidth += person.spouseList.length * 120; // 每个配偶占用200px
  }
  // 计算子代的宽度
  if (person.children && person.children.length > 0) {
    totalWidth += person.children.reduce((sum, child) => sum + getSubtreeWidth(child), 0);
  }
  return totalWidth;
};

// 计算每个子节点的X坐标
const childConnectorX = (childIdx: number) => {
  if (!props.person.children) return props.parentX;
  let totalOffset = 0;
  // 计算所有配偶的宽度
  if (props.person.spouseList && props.person.spouseList.length > 0) {
    totalOffset += props.person.spouseList.length * 120; // 每个配偶占用200px
  }
  // 计算每个子节点的宽度
  for (let i = 0; i < childIdx; i++) {
    totalOffset += getSubtreeWidth(props.person.children[i]);
  }
  return props.parentX + totalOffset;
};

// 获取头像显示文字
const getAvatarText = (person: Person) => {
  if (!person) return "?";

  if (person.firstName && person.firstName.length > 0) {
    return person.firstName.charAt(0);
  }

  if (person.lastName && person.lastName.length > 0) {
    return person.lastName.charAt(0);
  }

  return person.gender === 1 ? "男" : person.gender === 0 || person.gender === 2 ? "女" : "?";
};

function onNodeCardClick(event: any) {
  event.stopPropagation(); // 阻止事件冒泡
  currentMenuPerson.value = props.person;
  showMenu.value = !showMenu.value;
}

function onSpouseCardClick(spouse: Person, event: any) {
  event.stopPropagation(); // 阻止事件冒泡
  currentMenuPerson.value = spouse;
  showMenu.value = !showMenu.value;
}

function handleClickOutside() {
  if (showMenu.value) {
    showMenu.value = false;
    currentMenuPerson.value = null;
  }
}

onMounted(() => {
  document.addEventListener("click", handleClickOutside);
});

onBeforeUnmount(() => {
  document.removeEventListener("click", handleClickOutside);
});

// 主节点菜单列表
const menuList = computed(() => {
  const list = [
    {
      label: "新增子辈",
      action: () => {
        onAddChild(props.person);
        showMenu.value = false;
      },
    },
    {
      label: "编辑信息",
      action: () => {
        onEditInfo(props.person);
        showMenu.value = false;
      },
    },
    {
      label: "新增配偶",
      action: () => {
        onAddSpouse(props.person);
        showMenu.value = false;
      },
    },
  ];
  if (!props.person.parentId) {
    list.unshift({
      label: "新增父辈",
      action: () => {
        onAddParent(props.person);
        showMenu.value = false;
      },
    });
  }
  return list;
});

// 配偶节点菜单列表
const spouseMenuList = computed(() => {
  return [
    {
      label: "编辑信息",
      action: () => {
        if (currentMenuPerson.value) {
          onEditSpouse(currentMenuPerson.value);
        }
        showMenu.value = false;
      },
    },
    {
      label: "新增子辈",
      action: () => {
        if (currentMenuPerson.value) {
          onAddChild(currentMenuPerson.value);
        }
        showMenu.value = false;
      },
    },
  ];
});

const menuStyle = computed<CSSProperties>(() => {
  return {
    position: "absolute",
    top: "100%",
    left: "0",
    zIndex: 1000,
  };
});

const showAddChildModal = ref(false);
const currentParent = ref<Person | null>(null);

// 选项数据（实际可从接口获取，这里举例写死）
const familyOptions = ref([
  { label: "河间李氏", value: "1" },
  { label: "其他家族", value: "2" },
]);
const zibeiOptions = ref([
  { label: "字辈A", value: "A" },
  { label: "字辈B", value: "B" },
]);
const genderOptions = ref([
  { label: "男", value: 1 },
  { label: "女", value: 0 },
]);
const aliveOptions = ref([
  { label: "在世", value: 1 },
  { label: "已故", value: 0 },
]);

// 添加父辈
function onAddParent(person: Person) {
  uni.navigateTo({
    url: `/pages/genealogy/person/add-parent?childId=${person.id}`,
  });
}

// 添加子辈
function onAddChild(person: Person) {
  uni.navigateTo({
    url: `/pages/genealogy/person/add-child?parentId=${person.id}`,
  });
}

// 编辑信息
function onEditInfo(person: Person) {
  uni.navigateTo({
    url: `/pages/genealogy/person/add-child?id=${person.id}&mode=edit`,
  });
}

// 添加配偶
function onAddSpouse(person: Person) {
  uni.navigateTo({
    url: `/pages/genealogy/person/add-spouse?parentId=${person.id}`,
  });
}

// 编辑配偶信息
function onEditSpouse(spouse: Person) {
  uni.navigateTo({
    url: `/pages/genealogy/person/add-spouse?id=${spouse.id}&parentId=${spouse.parentId}&mode=edit&flag=${spouse.flag || 0}`,
  });
}

function handleAddChild(childData: Person) {
  // 这里可以发请求，或直接添加到children
  if (!currentParent.value!.children) currentParent.value!.children = [];
  currentParent.value!.children.push(childData);
  showAddChildModal.value = false;
}
</script>

<style lang="scss" scoped>
/* 节点样式 */
.tree-node {
  position: absolute;
  width: 80px;
  height: 180px;
  z-index: 2;
  transition: all 0.3s ease;
}

/* 目标节点高亮样式 */
.tree-node.target-node {
  z-index: 1000;
  animation: targetPulse 2s ease-in-out infinite;
}

.tree-node.target-node .node-card {
  border: 3px solid #ff6b35;
  box-shadow: 0 0 20px rgba(255, 107, 53, 0.6);
  transform: scale(1.05);
}

/* 目标节点脉冲动画 */
@keyframes targetPulse {
  0%,
  100% {
    box-shadow: 0 0 20px rgba(255, 107, 53, 0.6);
    transform: scale(1.05);
  }
  50% {
    box-shadow: 0 0 30px rgba(255, 107, 53, 0.8);
    transform: scale(1.08);
  }
}

/* 目标节点高亮类（用于动态添加） */
.target-highlight {
  animation: targetHighlight 0.5s ease-in-out;
}

@keyframes targetHighlight {
  0% {
    transform: scale(1);
    box-shadow: 0 0 0 rgba(255, 107, 53, 0);
  }
  50% {
    transform: scale(1.1);
    box-shadow: 0 0 30px rgba(255, 107, 53, 0.8);
  }
  100% {
    transform: scale(1.05);
    box-shadow: 0 0 20px rgba(255, 107, 53, 0.6);
  }
}

.node-card {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #fff8e6, #fff0c0);
  border: 2px solid #f0c78a;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  box-sizing: border-box;
  position: relative;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.node-card.male {
  border-top: 5px solid #3c9cff;
}

.node-card.female {
  border-top: 5px solid #ff6b81;
}

.avatar-container {
  width: 60px;
  height: 60px;
  border-radius: 30px;
  background-color: #f0f0f0;
  border: 2px solid #ddd;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
  overflow: hidden;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-text {
  font-size: 28px;
  font-weight: bold;
  color: #666;
}

.node-info {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.node-name {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
  text-align: center;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.node-generation {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
  text-align: center;
}

.status-icon {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin-top: 5px;
}

.status-icon.alive {
  background-color: #52c41a;
  border: 1px solid #fff;
}

.status-icon.deceased {
  background-color: #999;
  border: 1px solid #fff;
}

/* 连接线样式 */
.connector-line {
  position: absolute;
  background-color: #aaa;
  height: 2px;
  z-index: 1;
}

.connector-line.vertical {
  width: 2px;
  height: 15px;
}

.heart-icon {
  position: absolute;
  font-size: 18px;
  color: #ff6b81;
  z-index: 1;
}

.node-menu {
  background: linear-gradient(135deg, #fffbe6 0%, #ffe7ba 100%);
  border: 1px solid #ffd591;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.18);
  min-width: 120px;
  padding: 6px 0;
  transition: box-shadow 0.2s;
}

.menu-item {
  padding: 10px 20px;
  cursor: pointer;
  font-size: 15px;
  color: #7c4a00;
  border-radius: 8px;
  transition:
    background 0.2s,
    color 0.2s;
}

.menu-item:hover {
  background: #ffd591;
  color: #d46b08;
}
</style>
